package com.ifox.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.ifox.entity.IFox;
import com.ifox.entity.IFoxColumn;
import com.ifox.entity.IFoxTable;

public class Utils {

	protected static Logger logger = LoggerFactory.getLogger(Utils.class);
	
	//项目运行路径，取决于bat文件的写法
	public static String projectPath = System.getProperty("user.dir");
	
	static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    static DocumentBuilder builder = null; 

    
	/**
	 * 所有交换接口文件放到项目file下，只识别xml文件
	 * @return
	 */
	public static Map<String,String> getFiles(){
		Map<String,String> map = new HashMap<String,String>();
		String path = projectPath + "\\file";
		File file = new File(path);
		for(String s : file.list()){
			if(s.endsWith(".ifox")){
				map.put(s, projectPath + "\\file\\" + s);
			}
		}
		return map;
	}
	
//	public static void createFile(String filename) {
//		try {
//			String path = projectPath + "\\file\\" + filename + ".ifox";
//			File file = new File(path);
//			if(!file.exists()){
//				file.createNewFile();
//			}
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//		}
//	} 
	
	public static boolean isExists(String filename) {
		String path = projectPath + "\\file\\" + filename + ".ifox";
		File file = new File(path);
		return file.exists();
	}
	
	@SuppressWarnings("rawtypes")
	public static IFox openIFox(String filename){
		String lineTXT = "";
		String read = "";
		String result = "";
		InputStreamReader reader = null;
		BufferedReader bufferedReader = null;
		IFox ifox = null;
		try {
			String path = projectPath + "\\file\\" + filename;
			String encoding = "UTF-8"; // 字符编码(可解决中文乱码问题 )
			File file = new File(path);
			if (file.isFile() && file.exists()) {
				reader = new InputStreamReader(new FileInputStream(file), encoding);
				bufferedReader = new BufferedReader(reader);
				while ((read=bufferedReader.readLine()) != null) {  
					lineTXT += read + "\r\n";
				}
				result = new String(decryptBASE64(lineTXT));
			} else {
				logger.error("找不到指定的文件！");
			}
			
			Map<String, Class> classMap = new HashMap<String, Class>(); 
			classMap.put("tables", IFoxTable.class);
			classMap.put("columns", IFoxColumn.class);

			JSONObject jsonObject = JSONObject.fromObject(result);
			ifox = (IFox) JSONObject.toBean(jsonObject, IFox.class,classMap);
		} catch (Exception e) {
			logger.error("读取文件内容操作出错！",e);
		} finally{
			try {
				bufferedReader.close();
			} catch (IOException e1) {
				logger.error("输入流关闭出错！",e1);
			}
			try {
				reader.close();
			} catch (IOException e) {
				logger.error("输入流关闭出错！",e);
			}
		}
//		System.out.println("read:"+result);
		return ifox;
	}
	
	public static void saveIFox(IFox ifox){
		JSONObject content = JSONObject.fromObject(ifox);
		logger.info(content.toString());
		BufferedWriter output = null;
		try {
//			System.out.println("write:"+content);
			String path = projectPath + "\\file\\" + ifox.getIfoxName() + ".ifox";
			output = new BufferedWriter(new FileWriter(path));
			output.write(encryptBASE64(content.toString().getBytes("utf-8")));
			output.flush();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		} finally{
			try {
				output.close();
			} catch (IOException e) {
				logger.error("输出流关闭出错！",e);
			}
		}
	}
	
	public static void delFile(String filename){
		String path = projectPath + "\\file\\" + filename;
		File file =  new File(path);
		if(file.exists()){
			file.delete();
		}
	}
	
	//解密
	public static byte[] decryptBASE64(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}
	
	//加密
	public static String encryptBASE64(byte[] key) throws Exception {
		return (new BASE64Encoder()).encodeBuffer(key);
	}
	
}
